就算我們已經有 Token 驗證、Cookie、Redux 權限管理,但「用戶的 Email 真的屬於他本人嗎?」這件事還沒確認。
為了避免 假帳號 / 垃圾註冊 / 偷別人信箱建立帳號,你可以開啟 Firebase Email Verification(電子郵件驗證)。
emailVerified = true
註冊後寄送驗證信
import { getAuth, createUserWithEmailAndPassword, sendEmailVerification } from "firebase/auth";
export const signupWithEmail = async (email, password) => {
const auth = getAuth();
const result = await createUserWithEmailAndPassword(auth, email, password);
// 寄送驗證信
await sendEmailVerification(result.user);
return {
message: "註冊成功,驗證信已寄出!請到信箱點擊連結完成驗證。",
user: result.user,
};
};
登入時檢查「有沒有驗證過 Email」
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";
export const loginWithEmailCheck = async (email, password) => {
const auth = getAuth();
const result = await signInWithEmailAndPassword(auth, email, password);
if (!result.user.emailVerified) {
throw new Error("尚未驗證 Email,請先到信箱點擊驗證連結!");
}
return result.user;
};
Redux / ProtectedRoute 也可以加「未驗證阻擋」
if (!user.emailVerified) {
return <p>請先驗證信箱才能使用本功能。</p>;
}
延伸:自訂驗證頁 + 重新寄送驗證信
你可以做一個 /verify-email
頁面,提供「重新寄送」按鈕:
import { getAuth, sendEmailVerification } from "firebase/auth";
export const resendVerificationEmail = async () => {
const auth = getAuth();
if (!auth.currentUser) throw new Error("尚未登入");
await sendEmailVerification(auth.currentUser);
return "驗證信已重新寄出!";
};